package org.example.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RedEnvelopUtil {
    // 二倍均值法生成红包金额列表
    public static List<BigDecimal> divideRedEnvelope(BigDecimal totalAmount, int num) {
        List<BigDecimal> amountList = new ArrayList<>();
        Random random = new Random();
        BigDecimal remainingAmount = totalAmount;
        int remainingNum = num;

        for (int i = 0; i < num - 1; i++) {
            // 计算当前可分配的最大金额，确保后续每个人至少能分到 0.01 元
            BigDecimal max = remainingAmount.divide(BigDecimal.valueOf(remainingNum), 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(2));
            // 生成一个 0 到 max 之间的随机数
            BigDecimal randomAmount = BigDecimal.valueOf(random.nextDouble()).multiply(max);
            // 确保金额至少为 0.01 元
            randomAmount = randomAmount.max(BigDecimal.valueOf(0.01));
            randomAmount = randomAmount.setScale(2, RoundingMode.HALF_UP);
            amountList.add(randomAmount);
            remainingAmount = remainingAmount.subtract(randomAmount);
            remainingNum--;
        }
        // 最后一个人拿走剩余的所有金额
        remainingAmount = remainingAmount.setScale(2, RoundingMode.HALF_UP);
        amountList.add(remainingAmount);
        return amountList;
    }

    public static void main(String[] args) {
        int num = 10;
        BigDecimal totalAmount1 = new BigDecimal("100.00");
        List<BigDecimal> amountList1 = divideRedEnvelope(totalAmount1, num);
        for (int i = 0; i < amountList1.size(); i++) {
            System.out.println("第 " + (i + 1) + " 个人抢到：" + amountList1.get(i) + " 元");
        }
    }
}
